import { API_CONFIG, STATUS_CODE, BUSINESS_CODE } from '../config/api.js'
import projectConfig from '../config/project.json'
import { $t } from '../utils/language.js'

// 活动请求计数器，确保并发请求时正确显示/隐藏加载器
let activeRequestCount = 0
let hideTimer = null

// 基础请求配置
const request = (options) => {
    return new Promise((resolve, reject) => {
        // 获取token
        const token = uni.getStorageSync('x-token')

        // 设置默认请求头
        const header = {
            'Content-Type': 'application/json',
            ...options.header
        }

        // 如果有token，添加到请求头 - 农场游戏使用x-token（不带Bearer）
        if (token) {
            header['x-token'] = token
            header['clientId'] = projectConfig.clientId
        }

        // 全局加载器 - 请求发起时展示（仅当从0到1时触发）
        // console.log('options.url', options.url)
        const notShowLoadingUrl = ['/user/land', '/user/land/operate', '/user/land/seeding', '/user/land/win']
        if (activeRequestCount === 0 && !notShowLoadingUrl.includes(options.url)) {
            if (hideTimer) {
                clearTimeout(hideTimer)
                hideTimer = null
            }
            uni.$emit('show-loading')
        }
        activeRequestCount += 1

        uni.request({
            url: API_CONFIG.BASE_URL + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header,
            timeout: API_CONFIG.TIMEOUT,
            success: (res) => {
                if (res.statusCode === STATUS_CODE.SUCCESS) {
                    // 根据实际API返回格式调整
                    if (res.data.code === BUSINESS_CODE.SUCCESS || res.data.success) {
                        resolve(res.data)
                    } else if (res.data.code === BUSINESS_CODE.UNAUTHORIZED) {
                        uni.showToast({
                            title: res.data.message || res.data.msg || 'Login expired, please log in again',
                            icon: 'none'
                        })
                        uni.removeStorageSync('x-token')
                        uni.removeStorageSync('userInfo')
                        uni.redirectTo({
                            url: '/pages/index/index'
                        })
                        reject(res.data)
                    } else {
                        uni.showToast({
                            title: res.data.message || $t('messages.msg' + String(res.data.code), $t('messages.msg501')) || 'Request failed',
                            icon: 'none'
                        })
                        reject(res.data)
                    }
                } else if (res.statusCode === STATUS_CODE.UNAUTHORIZED) {
                    // token过期，清除本地存储并跳转到登录页
                    uni.removeStorageSync('x-token')
                    uni.removeStorageSync('userInfo')
                    reject(res)
                } else {
                    // uni.showToast({
                    //     title: '网络错误',
                    //     icon: 'none'
                    // })
                    reject(res)
                }
            },
            fail: (err) => {
                console.log(err);
                // uni.showToast({
                //     title: '网络错误',
                //     icon: 'none'
                // })
                reject(err)
            },
            complete: () => {
                // 全局加载器 - 请求结束时关闭
                activeRequestCount = Math.max(0, activeRequestCount - 1)
                if (activeRequestCount === 0) {
                    // 延迟隐藏，避免瞬时闪烁
                    hideTimer = setTimeout(() => {
                        uni.$emit('hide-loading')
                        hideTimer = null
                    }, 150)
                }
            }
        })
    })
}

export default request